/*
 You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

 You may assume the two numbers do not contain any leading zero, except the number 0 itself.

 Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
 Output: 7 -> 0 -> 8
 */

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
let addTwoNumbers = function (l1, l2) {
    let listNode = null;
    let nowNode = null;
    let addNum = 0;
    while (!(l1 == null && l2 == null && addNum == 0)){
        let a = 0;
        if(l1 != null){
            a = l1.val;
        }
        let b = 0;
        if(l2 != null){
            b = l2.val;
        }
        let num = (a + b + addNum) % 10;
        addNum = parseInt((a + b + addNum) / 10);

        if (listNode == null) {
            listNode = new ListNode(num);
            nowNode = listNode;
        } else {
            nowNode.next = new ListNode(num);
            nowNode = nowNode.next;
        }
        if(l1 != null){
            l1 = l1.next;
        }
        if(l2 != null){
            l2 = l2.next;
        }
    }
    return listNode;
};

function ListNode(val) {
    this.val = val;
    this.next = null;
}
function getListNode(nums) {
    let listNode = null;
    let nowNode = null;
    for (let i = 0; i < nums.length; i++) {
        if (listNode == null) {
            listNode = new ListNode(nums[i]);
            nowNode = listNode;
        } else {
            nowNode.next = new ListNode(nums[i]);
            nowNode = nowNode.next;
        }
    }
    console.log(listNode);
    return listNode;
}

function printListNode(listNode) {
    if (listNode == null) {
        return null;
    }
    let array = [];
    do {
        array.push(listNode.val);
        listNode = listNode.next;
    } while (listNode != null);
    console.log(array);
}

printListNode(addTwoNumbers(getListNode([1]), getListNode([9,9])));
